package com.gyms.fragment;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.classic.okhttp.beans.HVMyOrderInfoBean;
import com.classic.okhttp.enums.Enum;
import com.classic.okhttp.services.IUserService;
import com.classic.okhttp.zmoumall.http.ObjectCallback;
import com.gyms.R;
import com.gyms.activity.OrderDetailActivity;
import com.gyms.adapter.MyOrderAdapter;
import com.gyms.base.BaseFragment;
import com.gyms.constant.Constants;
import com.gyms.manager.StateUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import click.OnRecyclerViewItemClick;
import constant.EventConstant;
import refresh.PtrClassicFrameLayout;
import refresh.PtrDefaultHandler;
import refresh.PtrFrameLayout;
import refresh.PtrHandler;
import utils.StringUtils;
import weight.CommonEmptyView;
import weight.UiEvent;
import weight.head_foot_recyclerView.EndlessRecyclerOnScrollListener;
import weight.head_foot_recyclerView.HeaderAndFooterRecyclerViewAdapter;
import weight.head_foot_recyclerView.LoadingFooter;
import weight.head_foot_recyclerView.RecyclerViewStateUtils;

/**
 * 我的订单fragment
 * ltx
 */

public class MyOrderFragment extends BaseFragment implements CommonEmptyView.UpdateClick, OnRecyclerViewItemClick {
    @BindView(R.id.rv_my_order)
    RecyclerView mRvMyOrder;
    @BindView(R.id.pf_my_order)
    PtrClassicFrameLayout mPtrMyOrder;
    private MyOrderAdapter mMyOrderAdapter;//我的订单的adapter
    private List<HVMyOrderInfoBean> mMyOrderList = new ArrayList<>();
    protected final static int PAGESIZE = 10;//页数
    protected int mPageIndex = 1;//页码
    private boolean isCanLoadMore=true;
    private boolean isRefresh;//当前是否是刷新的状态
    @BindView(R.id.search_empty)
    CommonEmptyView searchEmpty;

    private Enum.EnumOrderState mOrderState;
    @Override
    protected int getLayoutResId() {
        return R.layout.activity_mine_order;
    }
    @Override
    protected void initView() {
        initData();
        searchEmpty.setUpDateClick(this);
        createLoadingView("正在加载中",true);
        initOrderAdapter();
        EventBus.getDefault().register(this);
    }

    private void initData() {
      Bundle mBundle = getArguments();
        if(null!=mBundle){
           int mOrderType=mBundle.getInt(Constants.MY_ORDER_TYPE);
            mOrderState= StateUtils.getOrderState(mOrderType);
        }
    }

    public static MyOrderFragment newIntance(int tag){
        MyOrderFragment mProductFragment=new MyOrderFragment();
        Bundle mBundle=new Bundle();
        mBundle.putInt(Constants.MY_ORDER_TYPE,tag);
        mProductFragment.setArguments(mBundle);
        return mProductFragment;
    }

    @Override
    protected void initListener() {
        mPtrMyOrder.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                reFreshOrder();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }
        });
        mRvMyOrder.addOnScrollListener(mOnScrollListener);
        mMyOrderAdapter.setOnRecyclerViewItemClick(this);
    }

    @Override
    protected void processLogic() {
        reFreshOrder();
    }

    /**
     * 获取我的订单列表
     */

    private void getMyOrderInfo() {
        if (null != loadingView) {
            loadingView.show();
        }
        IUserService.getMyOrderInfo(getActivity(), mPageIndex, PAGESIZE, mOrderState,false, new ObjectCallback<ArrayList<HVMyOrderInfoBean>>() {
            @Override
            public void onSuccess(ArrayList<HVMyOrderInfoBean> response, String message) {
                dialogDis(mPtrMyOrder,searchEmpty);
                if (!isRefresh) {
                    RecyclerViewStateUtils.setFooterViewState(mRvMyOrder, LoadingFooter.State.Normal);
                } else {
                    mPtrMyOrder.refreshComplete();
                }
                if (null != response && response.size() != 0) {
                    if (isRefresh) {//刷新清空数据源
                        mMyOrderList.clear();
                    }
                    mMyOrderList.addAll(response);
                    mMyOrderAdapter.notifyDataSetChanged();
                } else {
                    if (isRefresh) {
                        showEmptyView(mPtrMyOrder,searchEmpty, 1);
                    } else {
                        mPageIndex--;
                        RecyclerViewStateUtils.setFooterViewState(mRvMyOrder, LoadingFooter.State.TheEnd);
                        isCanLoadMore=false;
                    }
                }
               dialogDis();
            }

            @Override
            public void onErrorT(int code, ArrayList<HVMyOrderInfoBean> response, String errorMessage) {
                dialogDis();
                if(isRefresh){
                    mPtrMyOrder.refreshComplete();
                }else{
                    mPageIndex--;
                    RecyclerViewStateUtils.setFooterViewState(mRvMyOrder, LoadingFooter.State.NetWorkError);
                }
            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                dialogDis();
                if(isRefresh){
                    mPtrMyOrder.refreshComplete();
                }else{
                    mPageIndex--;
                    RecyclerViewStateUtils.setFooterViewState(mRvMyOrder, LoadingFooter.State.NetWorkError);
                }
            }
        });
    }


    /**
     * 初始化适配器
     */
    private void initOrderAdapter() {
        LinearLayoutManager mMyOrderManager=new LinearLayoutManager(mContext);
        mMyOrderManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRvMyOrder.setLayoutManager(mMyOrderManager);
        mMyOrderAdapter = new MyOrderAdapter(getActivity());
        mMyOrderAdapter.setMyOrderList(mMyOrderList);
        HeaderAndFooterRecyclerViewAdapter headerAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(mMyOrderAdapter);
        mRvMyOrder.setAdapter(headerAndFooterRecyclerViewAdapter);
    }
    /**
     * 刷新
     */

    private void reFreshOrder() {
        isRefresh=true;
        isCanLoadMore=true;
        mPageIndex = 1;
        getMyOrderInfo();
    }

    /**
     * 加载更多
     */

    private void doLoadMore() {
        isRefresh=false;
        mPageIndex++;
        getMyOrderInfo();
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);//注销
        if(null!=mMyOrderAdapter){
            mMyOrderAdapter.cancelAllTimers();
        }
    }

    //Eventbus 接收刷新列表的方法
    @Subscribe
    public void doRefreshList(UiEvent mUiEvent){
        if(null!=mUiEvent){
            if(EventConstant.FLAG_REFRESH_MY_ORDER.equals(mUiEvent.getKey())){//刷新
                mPtrMyOrder.autoRefresh(true);
            }
        }
    }

    @Override
    public void onUpdateClick() {
        reFreshOrder();
    }

    /**
     * 上拉加载监听
     */

    private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            if(StringUtils.isNull(mRvMyOrder)){
                return;
            }
            LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(mRvMyOrder);
            if(state == LoadingFooter.State.Loading) {
                return;
            }

            if (isCanLoadMore) {
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRvMyOrder, PAGESIZE, LoadingFooter.State.Loading, null);
                doLoadMore();
            } else {
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRvMyOrder, PAGESIZE, LoadingFooter.State.TheEnd, null);
            }
        }
    };

    @Override
    public void onRecyclerItemClick(RecyclerView view, int pos) {
        if (view == mRvMyOrder) {
            HVMyOrderInfoBean myOrderInfoBean=mMyOrderList.get(pos);
            Bundle mBundle = new Bundle();
            mBundle.putString(Constants.FLAG_INTENT_GYM_ORDER_ID, mMyOrderList.get(pos).getOrderId());
            int isProductTag = myOrderInfoBean.getOrderType().value; //1 是场馆 2是产品
            mBundle.putInt(Constants.FALG_INTENT_PRODUCT_TAG, isProductTag);//是产品或者场馆
            mBundle.putString(Constants.FALG_INTENT_MY_ORDER, Constants.FALG_INTENT_MY_ORDER);//从我的订单进去入
            startActivity(OrderDetailActivity.class, mBundle, false);
        }
    }
}
